using System.Collections.Generic;

namespace Core
{
    public class ItemContainerMgr : Entity , IAwake
    {
        private Unit unit;
        private int itemInstanceId = 0;
        private readonly Dictionary<string, ItemContainer> containers = new Dictionary<string, ItemContainer>();

        void IAwake.Awake()
        {
            unit = GetParent<Unit>();
        }

        public ItemContainer Create(string key, int size)
        {
            if(containers.TryGetValue(key, out var container))
            {
                container?.Dispose();
            }
            container = this.AddChild<ItemContainer, Unit, string, int>(unit, key, size);
            containers[key] = container;
            return container;
        }

        public ItemContainer Get(string key) 
        { 
            containers.TryGetValue(key, out var container);
            return container;
        }

        public void Remove(string key)
        {
            if(containers.TryGetValue(key, out var container))
            {
                container?.Dispose();
                containers.Remove(key);
            }
        }

        public int GenerateItemID()
        {
            return itemInstanceId++;
        }

        public override void Dispose()
        {
            base.Dispose();

            foreach (var container in containers.Values)
            {
                container?.Dispose();
            }
            containers.Clear();
        }

    }

}
